'use strict';

const TAG_TABLE = 'tag';
const MAP_TABLE = 'pic_map_tag';
const ERR_CODE = require('../constants/errorCode');
const Service = require('egg').Service;

class TagService extends Service {
  async create(userId, tagName) {
    const { ctx, app } = this;
    try {
      // 检查标签是否被使用
      const result1 = await app.mysql.select(TAG_TABLE, {
        where: { user_id: userId, tag_name: tagName },
        limit: 1,
        offset: 0,
      });

      if (result1.length >= 1) throw (ERR_CODE.Tag_DuplicateTag);

      // 没有被使用的话就新建这个标签
      const result2 = await app.mysql.insert(TAG_TABLE, {
        user_id: userId,
        tag_name: tagName,
        create_time: app.mysql.literals.now,
        update_time: app.mysql.literals.now,
      });

      if (result2.affectedRows !== 1) throw (ERR_CODE.Tag_DBInsertFail);
      return result2.insertId;
    } catch (err) {
      switch (err) {
        case ERR_CODE.Tag_DuplicateTag:
          ctx.throw(422, '标签重复，创建失败', {
            errCode: ERR_CODE.Tag_DuplicateTag,
            description: '标签重复',
          });
          break;
        case ERR_CODE.Tag_DBInsertFail:
          ctx.throw(422, '数据库插入失败，相册创建失败', {
            errCode: ERR_CODE.Tag_DBInsertFail,
            description: '数据库插入失败',
          });
          break;
        default:
          throw (err);
      }
    }
  }

  async addTag(picId, tagId) {
    const { ctx, app } = this;

    try {
    // 检查标签是否被使用
      const result1 = await app.mysql.select(MAP_TABLE, {
        where: { pic_id: picId, tag_id: tagId },
        limit: 1,
        offset: 0,
      });
      if (result1.length >= 1) throw (ERR_CODE.Tag_DuplicateMAP);

      const result2 = await app.mysql.insert(MAP_TABLE, {
        pic_id: picId,
        tag_id: tagId,
        create_time: app.mysql.literals.now,
      });

      return result2.affectedRows === 1;
    } catch (err) {
      switch (err) {
        case ERR_CODE.Tag_DuplicateMAP:
          ctx.throw(422, '请勿重复为图片添加同一标签', {
            errCode: ERR_CODE.Tag_DuplicateMAP,
            description: '标签映射重复',
          });
          break;
        default:
          throw (err);
      }
    }
  }

  async delTag(picId, tagId) {
    const { app } = this;
    const sql = `DELETE FROM ${MAP_TABLE} WHERE pic_id = '${picId}' AND tag_id = '${tagId}';`;
    console.log(sql);
    await app.mysql.query(sql);
    return true;
  }

  async edit(userId, tagId, tagName) {
    const { ctx, app } = this;
    try {
      // 检查标签是否被使用
      const result1 = await app.mysql.select(TAG_TABLE, {
        where: { user_id: userId, tag_name: tagName },
        limit: 1,
        offset: 0,
      });

      if (result1.length >= 1) throw (ERR_CODE.Tag_DuplicateTag);

      // 没有被使用的话就更新这个标签
      const sql = `UPDATE ${TAG_TABLE} SET tag_name = '${tagName}',update_time = '${ctx.helper.getCurrentDatetime()}' WHERE tag_id = '${tagId}'`;
      const result2 = await app.mysql.query(sql);

      if (result2.affectedRows !== 1) throw (ERR_CODE.Tag_DBUpdateFail);
      return true;
    } catch (err) {
      switch (err) {
        case ERR_CODE.Tag_DuplicateTag:
          ctx.throw(422, '标签重复，修改失败', {
            errCode: ERR_CODE.Tag_DuplicateTag,
            description: '标签重复',
          });
          break;
        case ERR_CODE.Tag_EditFail:
          ctx.throw(422, '标签', {
            errCode: ERR_CODE.Tag_DBUpdateFail,
            description: '数据库更新失败',
          });
          break;
        default:
          throw (err);
      }
    }
  }

  async index(userId) {
    const { app } = this;
    const result = app.mysql.select(TAG_TABLE, {
      column: [ 'tag_id', 'tag_name', 'update_time', 'create_time' ],
      where: { user_id: userId },
    });
    return result;
  }

  async destory(tagId) {
    const { app } = this;
    await app.mysql.delete(TAG_TABLE, { tag_id: tagId });
    return true;
  }
}

module.exports = TagService;
